// 注意：组件已移至单独文件，将在HTML中通过script标签加载
// 组件将作为全局函数可用

// 定义默认的TeacherManagement组件作为备用方案
if (typeof window.TeacherManagement === 'undefined') {
    window.TeacherManagement = function() {
        const [message, setMessage] = React.useState('正在加载教师管理组件...');
        const [showRefresh, setShowRefresh] = React.useState(false);
        
        React.useEffect(() => {
            // 设置一个计时器，如果3秒后组件仍未加载，则提示用户
            const timer = setTimeout(() => {
                setMessage('教师管理组件加载延迟，请确保已正确引用相关文件。');
                setShowRefresh(true);
            }, 3000);
            
            return () => clearTimeout(timer);
        }, []);
        
        return React.createElement('div', { className: 'p-8 bg-white rounded-lg shadow-md mx-4 my-4' },
            React.createElement('h2', { className: 'text-xl font-bold text-gray-800 mb-4' }, '教师管理'),
            React.createElement('div', { className: 'p-6 border border-yellow-200 bg-yellow-50 rounded-lg' },
                React.createElement('p', { className: 'text-gray-700' }, message),
                showRefresh && React.createElement('button', {
                    onClick: () => window.location.reload(),
                    className: 'mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600'
                }, '刷新页面')
            ),
            React.createElement('div', { className: 'mt-6 text-sm text-gray-500' },
                React.createElement('p', null, '提示：确保以下文件已正确加载：'),
                React.createElement('ul', { className: 'list-disc pl-5 mt-2' },
                    React.createElement('li', null, 'assets/js/utils.js'),
                    React.createElement('li', null, 'assets/js/components/common.js'),
                    React.createElement('li', null, 'assets/js/components/UserFormModal.js'),
                    React.createElement('li', null, 'assets/js/pages/TeacherManagement.js')
                )
            )
        );
    };
}

// 获取用户信息函数（保持兼容性）
function getUserInfo() {
    return Utils.getUserInfo();
}

function AdminPage() {
    const [activeMenu, setActiveMenu] = React.useState('teacher');
    const [isMenuCollapsed, setIsMenuCollapsed] = React.useState(false);
    const [componentLoaded, setComponentLoaded] = React.useState({}); // 跟踪组件加载状态
    const userInfo = getUserInfo();
    
    // 监听组件加载完成事件
    React.useEffect(() => {
        const handleComponentLoaded = (event) => {
            const { componentName } = event.detail || {};
            if (componentName) {
                console.log(`${componentName}组件已加载完成，更新组件状态`);
                setComponentLoaded(prev => ({
                    ...prev,
                    [componentName]: true
                }));
            }
        };
        
        // 监听自定义组件加载事件
        window.addEventListener('TeacherManagementLoaded', handleComponentLoaded);
        window.addEventListener('StudentManagementLoaded', handleComponentLoaded);
        window.addEventListener('SubjectManagementLoaded', handleComponentLoaded);
        window.addEventListener('ScoreManagementLoaded', handleComponentLoaded);
        
        // 定期检查组件加载状态标志
        const checkComponentFlags = () => {
            const components = ['TeacherManagement', 'StudentManagement', 'SubjectManagement', 'ScoreManagement'];
            const newlyLoaded = {};
            
            components.forEach(compName => {
                if (window[compName + 'Loaded'] && !componentLoaded[compName]) {
                    newlyLoaded[compName] = true;
                }
            });
            
            if (Object.keys(newlyLoaded).length > 0) {
                setComponentLoaded(prev => ({ ...prev, ...newlyLoaded }));
            }
        };
        
        const intervalId = setInterval(checkComponentFlags, 300);
        
        return () => {
            window.removeEventListener('TeacherManagementLoaded', handleComponentLoaded);
            window.removeEventListener('StudentManagementLoaded', handleComponentLoaded);
            window.removeEventListener('SubjectManagementLoaded', handleComponentLoaded);
            window.removeEventListener('ScoreManagementLoaded', handleComponentLoaded);
            clearInterval(intervalId);
        };
    }, [componentLoaded]);
    
    // 当组件加载状态更新时强制重新渲染
    React.useEffect(() => {
        // 简单地访问activeMenu以确保依赖项正确，这会在componentLoaded更改时触发重新渲染
        const currentMenu = activeMenu;
    }, [componentLoaded]);

    // 渲染菜单图标
    const renderIcon = (iconKey) => {
        const iconProps = {
            className: 'w-5 h-5',
            fill: 'none',
            stroke: 'currentColor',
            viewBox: '0 0 24 24',
            strokeWidth: '2',
            strokeLinecap: 'round',
            strokeLinejoin: 'round'
        };
        
        const icons = {
            teacher: React.createElement('svg', iconProps,
                React.createElement('path', { d: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z' })
            ),
            student: React.createElement('svg', iconProps,
                React.createElement('path', { d: 'M12 14l9-5-9-5-9 5 9 5z' }),
                React.createElement('path', { d: 'M12 14l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14z' }),
                React.createElement('path', { strokeLinecap: 'round', strokeLinejoin: 'round', d: 'M12 14l9-5-9-5-9 5 9 5zm0 0l6.16-3.422a12.083 12.083 0 01.665 6.479A11.952 11.952 0 0012 20.055a11.952 11.952 0 00-6.824-2.998 12.078 12.078 0 01.665-6.479L12 14zm-4 6v-7.5l4-2.222' })
            ),
            subject: React.createElement('svg', iconProps,
                React.createElement('path', { d: 'M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253' })
            ),
            score: React.createElement('svg', iconProps,
                React.createElement('path', { d: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z' })
            )
        };
        
        return icons[iconKey] || null;
    };

    // 菜单配置
    const menus = [
        { key: 'teacher', name: '教师管理' },
        { key: 'student', name: '学生管理' },
        { key: 'subject', name: '学科管理' },
        { key: 'score', name: '成绩管理' }
    ];

    // 渲染内容区域
    const renderContent = () => {
        // 检查组件是否存在，如果不存在则返回错误提示组件或默认实现
        const getComponentOrFallback = (component, componentName) => {
            if (typeof component === 'undefined') {
                console.warn(`${componentName}组件未定义，使用默认组件并尝试自动加载`);
                
                // 如果是TeacherManagement且已有默认实现，则使用它
                if (componentName === 'TeacherManagement' && typeof window.TeacherManagement !== 'undefined') {
                    console.log('使用TeacherManagement的默认备用实现');
                    return React.createElement(window.TeacherManagement);
                }
                
                return React.createElement(DefaultFallbackComponent, { componentName });
            }
            return React.createElement(component);
        };

        // 创建默认的后备组件，确保在组件未加载时也能显示界面
        const DefaultFallbackComponent = (props) => {
            const { componentName } = props;
            const [attemptCount, setAttemptCount] = React.useState(0);
            const [isChecking, setIsChecking] = React.useState(true);
            const maxAttempts = 15; // 增加最大重试次数
            const [customMessage, setCustomMessage] = React.useState('');
            
            React.useEffect(() => {
                // 尝试直接获取备用组件，如果存在的话
                const getBackupComponent = () => {
                    // 如果是TeacherManagement，可以使用我们定义的默认实现
                    if (componentName === 'TeacherManagement' && typeof window.TeacherManagement !== 'undefined') {
                        return window.TeacherManagement;
                    }
                    return null;
                };
                
                // 立即检查一次组件是否已经可用
                const backupComponent = getBackupComponent();
                if (backupComponent) {
                    // 如果找到备用组件，直接渲染它
                    return React.createElement(backupComponent);
                }
                
                // 设置周期性检查组件是否已加载的定时器
                let checkInterval;
                let nextCheckTime = 500; // 初始检查间隔500ms
                
                const checkComponent = () => {
                    setAttemptCount(prev => {
                        const newCount = prev + 1;
                        
                        // 检查组件是否已加载
                        if (typeof window[componentName] !== 'undefined') {
                            setIsChecking(false);
                            clearInterval(checkInterval);
                            // 不需要完全刷新页面，使用React状态更新来重渲染
                            window.dispatchEvent(new CustomEvent(`${componentName}Ready`));
                            return newCount;
                        }
                        
                        // 如果达到最大重试次数，停止检查
                        if (newCount >= maxAttempts) {
                            setIsChecking(false);
                            clearInterval(checkInterval);
                            console.error(`组件 ${componentName} 加载超时，请刷新页面重试`);
                            setCustomMessage(`无法自动加载${componentName}组件。请检查文件路径是否正确并刷新页面。`);
                        } else if (newCount > maxAttempts / 2) {
                            // 随着尝试次数增加，增加检查间隔时间（指数退避策略）
                            clearInterval(checkInterval);
                            nextCheckTime = Math.min(nextCheckTime * 1.5, 2000); // 最大间隔2秒
                            checkInterval = setInterval(checkComponent, nextCheckTime);
                        }
                        
                        return newCount;
                    });
                };
                
                checkInterval = setInterval(checkComponent, nextCheckTime);
                
                return () => {
                    if (checkInterval) clearInterval(checkInterval);
                };
            }, [componentName]);
            
            // 返回加载中的UI
            return React.createElement('div', { className: 'p-8 text-center bg-white rounded-lg shadow-md mx-auto max-w-md' },
                React.createElement('div', { className: 'animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto mb-4' }),
                React.createElement('h2', { className: 'text-xl font-bold text-gray-800' }, '正在加载组件...'),
                React.createElement('p', { className: 'text-gray-600 mt-2' }, `正在加载 ${componentName} 组件 (${attemptCount}/${maxAttempts})`),
                React.createElement('button', {
                    onClick: () => window.location.reload(),
                    className: 'mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors'
                }, '立即刷新')
            );
        };
        

        
        switch (activeMenu) {
            case 'teacher':
                return getComponentOrFallback(window.TeacherManagement, 'TeacherManagement');
            case 'student':
                return getComponentOrFallback(window.StudentManagement, 'StudentManagement');
            case 'subject':
                return getComponentOrFallback(window.SubjectManagement, 'SubjectManagement');
            case 'score':
                return getComponentOrFallback(window.ScoreManagement, 'ScoreManagement');
            default:
                return getComponentOrFallback(window.TeacherManagement, 'TeacherManagement');
        }
    };

    const logout = () => {
        try {
            localStorage.removeItem('auth.loggedIn');
            localStorage.removeItem('auth.token');
            localStorage.removeItem('auth.userId');
            localStorage.removeItem('auth.username');
            localStorage.removeItem('auth.realName');
            localStorage.removeItem('auth.email');
        } catch (e) {}
        window.location.href = 'login.html';
    };

    return React.createElement('div', { className: 'flex flex-col h-screen bg-gray-100' },
        // 顶部导航栏
        React.createElement('div', { className: 'bg-[#1f2937] shadow-sm border-b border-gray-600' },
            React.createElement('div', { className: 'flex items-center justify-between px-6 py-4' },
                React.createElement('div', { className: 'flex items-center' },
                    React.createElement('h1', { className: 'text-xl font-bold text-white' }, '班级管理系统'),
                    React.createElement('span', { className: 'ml-4 text-sm text-gray-300' }, `欢迎，${userInfo.realName}`)
                ),
                React.createElement('button', {
                    onClick: logout,
                    className: 'px-4 py-2 text-sm text-gray-300 hover:text-white hover:bg-gray-600 rounded transition'
                }, '退出登录')
            )
        ),

        React.createElement('div', { className: 'flex flex-1 overflow-hidden' },
            // 左侧菜单
            React.createElement('div', { 
                className: `bg-[#1f2937] shadow-lg border-r border-gray-200 transition-all duration-300 ${
                    isMenuCollapsed ? 'w-16' : 'w-64'
                }` 
            },
                React.createElement('div', { 
                    className: `p-4 border-b border-gray-600 ${isMenuCollapsed ? 'p-2' : ''} flex items-center justify-between` 
                },
                    isMenuCollapsed ? 
                        React.createElement('h2', { 
                            className: 'text-lg font-semibold text-white text-center cursor-pointer w-full',
                            onClick: () => setIsMenuCollapsed(!isMenuCollapsed),
                            title: '展开菜单'
                        }, '≡') :
                        React.createElement('h2', { className: 'text-lg font-semibold text-white' }, '功能菜单'),
                    !isMenuCollapsed && React.createElement('button', {
                        onClick: () => setIsMenuCollapsed(!isMenuCollapsed),
                        className: 'p-1 text-gray-300 hover:text-white hover:bg-gray-600 rounded transition',
                        title: '折叠菜单'
                    }, '←')
                ),
                React.createElement('nav', { className: 'p-2' },
                    menus.map(menu => 
                        React.createElement('button', {
                            key: menu.key,
                            onClick: () => setActiveMenu(menu.key),
                            className: `w-full flex items-center px-4 py-3 mb-1 text-left rounded-lg transition-colors ${
                                activeMenu === menu.key 
                                    ? 'bg-[#0052d9] text-white' 
                                    : 'text-gray-300 hover:bg-gray-700'
                            } ${isMenuCollapsed ? 'justify-center px-2' : ''}`,
                            title: isMenuCollapsed ? menu.name : ''
                        },
                            renderIcon(menu.key),
                            !isMenuCollapsed && React.createElement('span', { className: 'font-medium ml-3' }, menu.name)
                        )
                    )
                )
            ),

            // 右侧内容区域
            React.createElement('main', { className: 'flex-1 overflow-auto' },
                renderContent()
            )
        )
    );
}

// 页面加载完成后初始化组件
window.addEventListener('DOMContentLoaded', () => {
    // 添加调试代码检查组件是否正确加载到全局作用域
    console.log('Global components check:');
    console.log('TeacherManagement exists:', typeof window.TeacherManagement !== 'undefined');
    console.log('StudentManagement exists:', typeof window.StudentManagement !== 'undefined');
    console.log('SubjectManagement exists:', typeof window.SubjectManagement !== 'undefined');
    console.log('ScoreManagement exists:', typeof window.ScoreManagement !== 'undefined');
    console.log('UserFormModal exists:', typeof window.UserFormModal !== 'undefined');
    console.log('DataTable exists:', typeof window.DataTable !== 'undefined');
    
    // 直接渲染AdminPage组件
    ReactDOM.render(React.createElement(AdminPage), document.getElementById('root'));
});

// UserFormModal已从components/UserFormModal.js导入，此处不再重复定义
// StudentManagement组件已从单独文件导入，此处不再重复定义
// SubjectManagement组件已从单独文件导入，此处不再重复定义
// ScoreManagement组件已从单独文件导入，此处不再重复定义